// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package config_cmd

import (
	"fmt"
	"os"
	"os/user"
	"strings"
	"syscall"

	"atomgit.com/openlinksaas-org/proto-gen-go.git/project_server_api"
	"gitcode.com/opendragonfly/df_server/config"
	"gitcode.com/opendragonfly/df_server/utils"
	"github.com/dchest/uniuri"
	"github.com/spf13/cobra"
)

var addRemoteCmd_serverAddr string

var addRemoteCmd = &cobra.Command{
	Use: "addRemote",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 3 {
			return fmt.Errorf("need param [token] [name] [pubIp]")
		}
		return nil
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		//检查是否是root用户
		curUser, err := user.Current()
		if err != nil {
			return err
		}
		if curUser.Uid != "0" {
			return fmt.Errorf("need root to run this command")
		}

		token := args[0]
		name := args[1]
		pubIp := args[2]

		if strings.Contains(pubIp, ":") {
			parts := strings.Split(pubIp, ":")
			pubIp = parts[0]
		}

		cfg, err := config.ReadServerConfig()
		if err != nil {
			return err
		}
		conn, err := utils.ConnGrpcServer(addRemoteCmd_serverAddr)
		if err != nil {
			return err
		}
		defer conn.Close()

		client := project_server_api.NewProjectServerApiClient(conn)
		shareSecret := uniuri.NewLenChars(64, []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
		res, err := client.JoinByJoinToken(cmd.Context(), &project_server_api.JoinByJoinTokenRequest{
			Token:       token,
			ServerName:  name,
			ServerAddr:  fmt.Sprintf("%s:%d", pubIp, cfg.Port.ServicePort),
			ShareSecret: shareSecret,
		})
		if err != nil {
			return err
		}
		remoteList := []*config.RemoteConfig{}
		for _, remoteCfg := range cfg.RemoteList {
			if remoteCfg.RemoteId != res.ServerId {
				remoteList = append(remoteList, remoteCfg)
			}
		}
		remoteList = append(remoteList, &config.RemoteConfig{
			RemoteId:    res.ServerId,
			RemoteAddr:  addRemoteCmd_serverAddr,
			ProjectId:   res.ProjectId,
			ShareSecret: shareSecret,
		})
		cfg.RemoteList = remoteList
		err = config.WriteServerConfig(cfg)
		if err != nil {
			return err
		}
		fmt.Println("add remote success")

		pid, err := utils.LoadPid()
		if err == nil {
			p, err := os.FindProcess(pid)
			if err == nil {
				p.Signal(syscall.SIGHUP)
				fmt.Println("send SIGHUP to process")
			}
		}
		return nil
	},
}

func init() {
	addRemoteCmd.Flags().StringVar(&addRemoteCmd_serverAddr, "serverAddr", "serv.linksass.pro:5000", "set linksaas server address")
}
